package org.example.Servlet.vote;

import cn.hutool.json.JSONUtil;
import org.example.Dao.VoteDao;
import org.example.entity.VoteChar;
import org.example.entity.VoteCharResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/vote/chart")
public class VotingChartServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        VoteDao voteDao = new VoteDao();
        int tid = Integer.parseInt(req.getParameter("tid"));
        VoteCharResult voteCharResult = new VoteCharResult();
        try {
            // 获取每个选项的投票数据
            List<VoteChar> chars = voteDao.getCharInfo(tid);
            voteCharResult.setVoteChars(chars);
            // 获取该主题的总投票数量
            int voteCount = voteDao.getVoteCount(tid);
            voteCharResult.setCount(voteCount);
            resp.getWriter().write(JSONUtil.toJsonStr(voteCharResult));
        } catch (Exception e) {
            System.out.println("vote char result error ==> " + e.getMessage());
        }
    }
}
